const { Op, literal } = require("sequelize");
const Category = require("../models/Category.js");

class CategoryService {
    async addCategory(categoryData){
        return Category.create(categoryData);
    }
    async getCategoryById(id){
        return Category.findByPk(id);
    }
    async getAllCategorys(){
        return Category.findAll();
    }
    async updateCategory(categoryData){
        return Category.update(categoryData, {
            where: {
                id: categoryData.id
            }
        });
    }
    async deleteCategory(categoryId){
        return Category.destroy({
            where: {
                id: categoryId
            }
        });
    }
    async getCategoryListByPage(page = 1, limit = 10, keyword = undefined){
        return Category.findAndCountAll({
            limit,
            offset: (page - 1) * limit,
            where: {
                deleted_at: null,
                [Op.or]: [
                    {
                      name: {
                        [Op.like]: `%${keyword}%`,
                      },
                    }
                  ],
            },
            attributes: [
                'id',
                'name',
                [literal('DATE_FORMAT(created_at, "%Y-%m-%d %H:%i:%s")'), 'created_at'],
                [literal('DATE_FORMAT(updated_at, "%Y-%m-%d %H:%i:%s")'), 'updated_at'],
                [literal('DATE_FORMAT(deleted_at, "%Y-%m-%d %H:%i:%s")'), 'deleted_at'],
            ]
        });
    }
}

module.exports = new CategoryService();